package com.skivingcloud.admin.shiro.filter;

import com.skivingcloud.common.utils.JsonUtils;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.common.utils.StringUtils;
import net.sf.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * shiro session失效处理
 * @author hushouquan
 *
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter{
	
//	@Autowired
//	private CommonPropertiesConfig commonPropertiesConfig;
	
	private String feignAccessToken;
	
	/**
	 * 
	 * @param feignAccessToken
	 */
	public CustomFormAuthenticationFilter(String feignAccessToken) {
		this.feignAccessToken=feignAccessToken;
	}

	@Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONS
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        //含有feignAccessToken说明是feign调用，token匹配则直接通过验证
        String accessToken = ((HttpServletRequest) request).getHeader("feignAccessToken");
		if(StringUtils.isBlank(accessToken)){
			accessToken = request.getParameter("feignAccessToken");
		}
        if(feignAccessToken.equals(accessToken)) {
        	return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }
	
	@Override  
    protected boolean onAccessDenied(ServletRequest arg0, ServletResponse arg1) throws Exception {  
		 HttpServletResponse response =(HttpServletResponse) arg1;
		 String requestURI = getPathWithinApplication(arg0);
		 System.out.print("requestURI"+requestURI);
		 
		 try {
	    	   JSONObject returnObj = new JSONObject();
	    	   returnObj.element("httpCode", "SHIRO_EXPIRE");//shiro session 获取
	   		   response.setContentType("application/json; charset=utf-8");
			   response.setCharacterEncoding("UTF-8");
//			   response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
//			   response.addHeader("Access-Control-Allow-Headers", "*");
//			   response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
//			   response.addHeader("Access-Control-Allow-Credentials", "true");
			   R r = R.error(HttpStatus.SC_UNAUTHORIZED, "由于权限不足请求被拒绝");//没权限直接返回401
			   //response.getWriter().print(returnObj.toString());
			   response.getWriter().write(JsonUtils.mapToJson(r));
			   response.getWriter().close();
	       } catch (IOException e) {
	           e.printStackTrace();
	       }
		 return false;
//		 return super.onAccessDenied(request, response);  
      
    }  
}
